<template>
  <div class="product-audit-container">
    <div class="page-header animate__animated animate__fadeInDown">
      <div class="title-box">
        <i class="el-icon-s-check title-icon"></i>
        <h2>商品审核管理</h2>
      </div>
      <el-button type="primary" @click="loadData" icon="el-icon-refresh" class="refresh-btn">刷新数据</el-button>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stat-cards animate__animated animate__fadeInDown">
      <el-card shadow="hover" class="stat-card">
        <div class="stat-card-content">
          <i class="el-icon-s-goods stat-icon pending"></i>
          <div class="stat-info">
            <div class="stat-label">待审核</div>
            <div class="stat-value">{{ getPendingCount() }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 商品表格 -->
    <div class="table-container animate__animated animate__fadeInUp">
      <div class="table-section">
        <el-table 
          :data="tableData" 
          border 
          stripe 
          highlight-current-row
          style="width: 100%"
          v-loading="loading"
          :header-cell-style="getRowClass"
          element-loading-text="加载中..."
          element-loading-spinner="el-icon-loading"
          row-class-name="table-row">
          <el-table-column prop="productId" label="商品ID" width="70" align="center"></el-table-column>
          <el-table-column prop="productName" label="商品名称" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column prop="price" label="价格" width="80">
            <template slot-scope="scope">
              <span class="price-tag">¥{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="origin" label="产地" width="80"></el-table-column>
          <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              <span class="description-text">{{ scope.row.description || '暂无描述' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="traceCode" label="溯源码" width="100" show-overflow-tooltip></el-table-column>
          <el-table-column prop="createUserId" label="创建者ID" width="80" align="center"></el-table-column>
          <el-table-column prop="auditStatusText" label="审核状态" width="90" align="center">
            <template slot-scope="scope">
              <el-tag 
                :type="getAuditStatusType(scope.row.auditStatus)" 
                effect="dark" 
                size="medium">
                {{ scope.row.auditStatusText || '待审核' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template slot-scope="scope">
              <div class="operation-buttons">
                <el-button size="mini" type="primary" @click="handleView(scope.row)" icon="el-icon-view" class="action-btn">查看</el-button>
                <el-button 
                  size="mini" 
                  type="success" 
                  @click="handleAudit(scope.row, 1)" 
                  icon="el-icon-check"
                  class="action-btn"
                  v-if="scope.row.auditStatus === 0">
                  通过
                </el-button>
                <el-button 
                  size="mini" 
                  type="danger" 
                  @click="handleAudit(scope.row, 2)" 
                  icon="el-icon-close"
                  class="action-btn"
                  v-if="scope.row.auditStatus === 0">
                  拒绝
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="block pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pageSize"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 查看商品对话框 -->
    <el-dialog 
      title="商品详情" 
      :visible.sync="detailDialogVisible" 
      :width="dialogWidth"
      center
      top="10vh"
      :close-on-click-modal="false"
      custom-class="custom-dialog">
      <el-card shadow="never" class="detail-card">
        <div class="detail-header">
          <h3>{{ form.productName }}</h3>
          <el-tag
            :type="getAuditStatusType(form.auditStatus)"
            effect="dark"
            size="medium">
            {{ form.auditStatusText || '待审核' }}
          </el-tag>
        </div>
        <el-divider></el-divider>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商品ID">{{ form.productId }}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ form.productName }}</el-descriptions-item>
          <el-descriptions-item label="价格">
            <span class="price-tag">¥{{ form.price }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="产地">{{ form.origin }}</el-descriptions-item>
          <el-descriptions-item label="溯源码">{{ form.traceCode }}</el-descriptions-item>
          <el-descriptions-item label="最低温度">{{ form.minTemp }}°C</el-descriptions-item>
          <el-descriptions-item label="最高温度">{{ form.maxTemp }}°C</el-descriptions-item>
          <el-descriptions-item label="采摘时间">{{ form.harvestTime }}</el-descriptions-item>
          <el-descriptions-item label="创建者ID">{{ form.createUserId }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            <div class="description-box">{{ form.description || '暂无描述' }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false" plain>关闭</el-button>
        <el-button 
          type="success" 
          @click="handleAudit(form, 1)" 
          icon="el-icon-check"
          v-if="form.auditStatus === 0">
          通过审核
        </el-button>
        <el-button 
          type="danger" 
          @click="handleAudit(form, 2)" 
          icon="el-icon-close"
          v-if="form.auditStatus === 0">
          拒绝审核
        </el-button>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog 
      :title="auditForm.status === 1 ? '审核通过' : '审核拒绝'" 
      :visible.sync="auditDialogVisible" 
      :width="dialogWidth"
      center
      :close-on-click-modal="false"
      custom-class="custom-dialog">
      <el-form :model="auditForm" label-width="120px" :rules="auditRules" ref="auditForm" class="audit-form">
        <el-form-item label="审核意见" prop="comment">
          <el-input 
            type="textarea" 
            v-model="auditForm.comment" 
            :rows="4" 
            :placeholder="auditForm.status === 1 ? '请输入通过理由...' : '请输入拒绝理由...'"
            resize="none">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false" plain>取消</el-button>
        <el-button 
          :type="auditForm.status === 1 ? 'success' : 'danger'"
          @click="submitAudit"
          :icon="auditForm.status === 1 ? 'el-icon-check' : 'el-icon-close'">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import 'animate.css/animate.min.css';

export default {
  name: 'ProductAudit',
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      detailDialogVisible: false,
      auditDialogVisible: false,
      loading: false,
      form: {},
      auditForm: {
        productId: null,
        status: 1,
        comment: '',
        addToStore: true
      },
      auditRules: {
        comment: [
          { required: true, message: '请输入审核意见', trigger: 'blur' },
          { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
        ]
      },
      userId: null,
      roleId: null,
      dialogWidth: window.innerWidth < 768 ? '95%' : '50%'
    };
  },
  created() {
    // 监听窗口大小变化，调整对话框宽度
    window.addEventListener('resize', this.handleResize);
    
    // 从本地存储获取用户信息
    const userStr = localStorage.getItem('user');
    if (userStr) {
      const user = JSON.parse(userStr);
      this.userId = user.id;
      this.roleId = user.roleId;

      // 检查用户角色是否为管理员
      if (this.roleId !== 1 && this.roleId !== 2) {
        this.$message.warning('只有管理员才能访问此页面');
        this.$router.push('/home');
        return;
      }
    } else {
      this.$message.error('未登录或登录已过期');
      this.$router.push('/login');
      return;
    }

    this.loadData();
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    // 处理窗口大小变化
    handleResize() {
      this.dialogWidth = window.innerWidth < 768 ? '95%' : '50%';
    },
    // 加载待审核的商品数据
    loadData() {
      this.loading = true;
      this.request.get('/product/admin/pending').then(res => {
        this.loading = false;
        if (res.code === '200') {
          this.tableData = res.data || [];
          this.total = this.tableData.length;
        } else {
          this.$message.error(res.msg || '获取待审核商品列表失败');
        }
      }).catch(() => {
        this.loading = false;
        this.$message.error('网络异常，请稍后重试');
      });
    },
    // 表格头部样式
    getRowClass({rowIndex, columnIndex}) {
      if(rowIndex === 0) {
        return 'background:#ccc'
      }
    },
    // 处理分页大小变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadData();
    },
    // 处理页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadData();
    },
    // 查看商品详情
    handleView(row) {
      this.form = { ...row };
      this.detailDialogVisible = true;
    },
    // 审核商品
    handleAudit(row, status) {
      this.auditForm = {
        productId: row.productId,
        status: status,
        comment: '',
        addToStore: status === 1
      };
      this.auditDialogVisible = true;
    },
    // 提交审核
    submitAudit() {
      this.$refs.auditForm.validate(valid => {
        if (valid) {
          this.loading = true;
          this.request.post(`/product/admin/audit/${this.auditForm.productId}`, {
            auditUserId: this.userId,
            auditStatus: this.auditForm.status,
            auditComment: this.auditForm.comment
          }).then(res => {
            if (res.code === '200') {
              this.$message({
                type: 'success',
                message: this.auditForm.status === 1 ? '审核通过' : '审核拒绝',
                duration: 2000
              });
              this.auditDialogVisible = false;
              this.loadData();
              if (this.detailDialogVisible) {
                this.detailDialogVisible = false;
              }
            } else {
              this.loading = false;
              this.$message.error(res.msg || '审核失败');
            }
          }).catch(() => {
            this.loading = false;
            this.$message.error('网络异常，请稍后重试');
          });
          return false;
        }
      });
    },
    // 获取审核状态类型
    getAuditStatusType(status) {
      const types = {
        0: 'info',     // 待审核
        1: 'success',  // 审核通过
        2: 'danger'    // 审核拒绝
      };
      return types[status] || 'info';
    },
    // 获取待审核数量
    getPendingCount() {
      return this.tableData.filter(item => item.auditStatus === 0).length;
    }
  }
};
</script>

<style scoped>
.product-audit-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-box {
  display: flex;
  align-items: center;
}

.title-icon {
  font-size: 26px;
  margin-right: 10px;
  color: #409EFF;
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

.refresh-btn {
  padding: 10px 20px;
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s;
}

.refresh-btn:hover {
  transform: scale(1.02);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-cards {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 20px;
  gap: 20px;
}

.stat-card {
  width: 250px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.stat-card-content {
  display: flex;
  align-items: center;
  padding: 5px;
}

.stat-icon {
  font-size: 36px;
  margin-right: 15px;
  border-radius: 50%;
  padding: 15px;
}

.stat-icon.pending {
  background-color: rgba(144, 147, 153, 0.1);
  color: #909399;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.table-row {
  transition: all 0.3s;
}

.table-row:hover {
  background-color: #f5f7fa !important;
}

.price-tag {
  color: #ff6b6b;
  font-weight: bold;
}

.operation-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap; /* 允许按钮在空间不足时换行 */
  justify-content: center;
}

.action-btn {
  margin: 2px;
  transition: all 0.2s;
}

.action-btn:hover {
  transform: scale(1.05);
}

.custom-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.custom-dialog .el-dialog__header {
  background: #f5f7fa;
  padding: 15px 20px;
}

.custom-dialog .el-dialog__title {
  font-weight: 600;
  color: #303133;
}

.custom-dialog .el-dialog__body {
  padding: 25px;
}

.detail-card {
  border: none;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.detail-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.description-box {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  min-height: 80px;
  line-height: 1.6;
}

.dialog-footer {
  text-align: right;
  padding-top: 10px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.audit-form {
  margin: 10px 0;
}

.audit-form .el-textarea__inner {
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.6;
  transition: all 0.3s;
}

.audit-form .el-textarea__inner:focus {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.add-to-store-tip {
  font-size: 13px;
  color: #606266;
  margin-left: 10px;
}

.audit-form .el-form-item {
  margin-bottom: 22px;
}

@media screen and (max-width: 768px) {
  .stat-cards {
    flex-direction: column;
  }
  
  .stat-card {
    margin-bottom: 10px;
    width: 100%; /* 在小屏幕上占满宽度 */
  }
  
  /* 小屏幕下表格的响应式处理 */
  .el-table {
    width: 100%;
  }
  
  /* 对话框内容居中 */
  .el-descriptions-item__content,
  .el-descriptions-item__label {
    text-align: left !important;
    word-break: break-word;
  }
  
  /* 调整对话框宽度 */
  .custom-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
}

/* 添加表格头部样式，与产品页保持一致 */
.el-table th {
  background-color: #ccc !important;
  color: #303133;
  font-weight: bold;
}

.el-table {
  margin-top: 10px;
}

.el-button {
  margin: 0;
}

/* 添加分页容器样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 10px 0;
  width: 100%;
}

/* 描述文本样式 */
.description-text {
  color: #606266;
  font-size: 13px;
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style> 